// register.js
import { NextResponse } from "next/server";
import connect from "@/utils/mongodb";
import User from "@/model/User";
import bcrypt from "bcryptjs";
import { verificationDB } from '@/utils/verificationDB';

// 新增：获取客户端IP的工具函数（与登录接口保持一致）
const getClientIp = (request) => {
  // 从请求头获取IP（适配不同环境，如反向代理）
  ip = request.headers.get("x-forwarded-for")?.split(",")[0] ||
    request.headers.get("x-real-ip") ||
    "未知IP";
  console.debug("获取到的ip地址: ", ip)
  return ip;
};

export const POST = async (request) => {
  try {
    const data = await request.json();
    const { name, email, password, verificationCode } = data;

    // 1. 基础参数校验
    if (!name || !email || !password || !verificationCode) {
      return NextResponse.json({
        message: "请输入完整参数（name, email, password, verificationCode）",
        success: false
      }, { status: 400 });
    }

    // 2. 验证码校验（保持不变）
    const storedCodeInfo = await verificationDB.findOne({ email });
    if (!storedCodeInfo) {
      return NextResponse.json({
        message: "未找到验证码记录，请重新获取验证码",
        success: false
      }, { status: 400 });
    }
    if (storedCodeInfo.code !== verificationCode) {
      return NextResponse.json({ message: "验证码错误", success: false }, { status: 400 });
    }
    if (storedCodeInfo.expires < Date.now()) {
      return NextResponse.json({ message: "验证码已过期，请重新获取", success: false }, { status: 400 });
    }

    // 3. 删除验证码记录（保持不变）
    await verificationDB.remove({ email }, { multi: true });

    // 4. 获取注册IP（新增逻辑）
    const registerIp = getClientIp(request);

    // 5. 连接数据库并保存用户
    await connect();

    // 检查邮箱/用户名是否已注册（保持不变）
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      return NextResponse.json({ message: "该邮箱已被注册", success: false }, { status: 400 });
    }
    const existingName = await User.findOne({ name });
    if (existingName) {
      return NextResponse.json({ message: "该用户名已被注册", success: false }, { status: 400 });
    }

    // 6. 加密密码并保存用户（新增registerIp字段）
    const hashedPassword = await bcrypt.hash(password, 10);
    const newUser = new User({
      name,
      email,
      password: hashedPassword,
      registerIp: registerIp // 保存注册时的IP
    });
    const savedUser = await newUser.save();

    if (savedUser._id) {
      return NextResponse.json({
        message: "注册成功",
        success: true
      }, { status: 201 });
    } else {
      throw new Error("用户保存失败");
    }

  } catch (error) {
    console.error("注册接口错误:", error);
    if (error.code === 11000) {
      const key = Object.keys(error.keyPattern)[0];
      return NextResponse.json({
        message: key === "email" ? "该邮箱已被注册" : "该用户名已被注册",
        success: false
      }, { status: 400 });
    }
    return NextResponse.json({
      message: "注册失败：" + error.message,
      success: false
    }, { status: 500 });
  }
};